<template>
  <div class="production-plan">
    <el-button type="success" @click="addjihau" class="save-button">保存主表单和明细</el-button>
    <h3 class="title"> 包装成品质检</h3>

    <!-- 基本信息 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="120px"
             class="form-container">
      <el-row :gutter="30">
        <!-- 第一行 -->
        <el-col :span="8">
          <el-form-item label="生产批号">
            <el-input
              placeholder="请输入"
              v-model="formData.batchNumber"
              required
            >
              <template #suffix>
                <el-button size="mini" @click="openAssociatedItemDialog1">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产时间" prop="productionDate" style="margin-bottom: 20px;">
            <el-date-picker
              v-model="formData.productionDate"
              type="date"
              required
              placeholder="请选择事务起始时间"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装类型">
            <el-select v-model="formData.packagingType" placeholder="选择包装类型">
              <el-option label="瓶装" value="瓶装"/>
              <el-option label="灌装" value="灌装"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装标签质量">
            <el-select v-model="formData.labelQuality" placeholder="选择包装标签质量"> <!-- 修改了 placeholder -->
              <el-option label="好" value="好"/>
              <el-option label="一般" value="一般"/>
              <el-option label="差" value="差"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装密封情况">
            <el-select v-model="formData.capSealing" placeholder="选择包装密封情况">
              <el-option label="密封" value="密封"/>
              <el-option label="松动" value="松动"/>
              <el-option label="泄漏" value="泄漏"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装状况">
            <el-select v-model="formData.bottleCondition" placeholder="选择包装状况">
              <el-option label="完好" value="完好"/>
              <el-option label="破裂" value="破裂"/>
              <el-option label="有划痕" value="有划痕"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灌装液位">
            <el-select v-model="formData.fillLevel" placeholder="选择灌装液位">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装材料柔韧性">
            <el-select v-model="formData.flexibility" placeholder="选择包装材料柔韧性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装材料耐水性">
            <el-select v-model="formData.waterResistance" placeholder="选择包装材料耐水性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装材料透气性">
            <el-select v-model="formData.breathability" placeholder="选择包装材料透气性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装表面平整度">
            <el-select v-model="formData.surfaceFlatness" placeholder="选择包装表面平整度">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装颜色一致性">
            <el-select v-model="formData.colorConsistency" placeholder="选择包装颜色一致性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检日期" prop="inspectionDate" style="margin-bottom: 20px;">
            <el-date-picker
              v-model="formData.inspectionDate"
              type="date"
              required
              placeholder="请选择质检日期"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检人员姓名" style="margin-bottom: 20px;">
            <el-input v-model="formData.inspectorName" placeholder="请输入质检人员姓名"/> <!-- 修改了 placeholder -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检结果">
            <el-select v-model="formData.inspectionResult" placeholder="选择质检结果"> <!-- 修改了 placeholder -->
              <el-option label="true" value="true"/> <!-- 修改了 label 使其更易读 -->
              <el-option label="false" value="false"/> <!-- 修改了 label 使其更易读 -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注信息" style="margin-bottom: 20px;">
            <el-input v-model="formData.remarks" placeholder="请输入" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog
      v-model="associatedItemDialogVisible1"
      width="500px"
      title="生产批次信息选择"
      append-to-body
    >
      <el-table
        :data="associatedItems1"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange1"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="itemName" label="物料名称" />
        <el-table-column property="itemspecification" label="物料规格" />
        <el-table-column property="itemType" label="物料类型" />
        <el-table-column property="lotNumber" label="批次号" />
        <el-table-column property="manufactureDate" label="生产日期" />
        <el-table-column property="expirationDate" label="有效期" />
        <el-table-column property="plannedQuantity" label="计划备料数量" />
        <el-table-column property="actualQuantity" label="实际备料数量" />
        <el-table-column property="unit" label="单位" />
        <el-table-column property="packagingPlanId" label="计划主键" />
        
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem1">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
import axios from 'axios';
// 未使用到 th，移除该导入
// import { th } from 'element-plus/es/locales.mjs';

const formRef = ref(null);
const currentUser = ref("admin");
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
  "id": '',
  "batchNumber": "",
  "productionDate": "",
  "packagingType": "",
  "labelQuality": "",
  "capSealing": "",
  "bottleCondition": "",
  "fillLevel": "",
  "flexibility": "",
  "waterResistance": "",
  "breathability": "",
  "surfaceFlatness": "",
  "colorConsistency": "",
  "inspectionDate": new Date().toISOString(),
  "inspectorName": currentUser.value,
  "inspectionResult": true,
  "remarks": "",
  "isDel": true,
  "request": "" // 补充此字段
});
// 主表单验证规则，确保规则中的属性在 formData 中存在
const rules = reactive({
  batchNumber: [
    { required: true, message: '生产批号不能为空', trigger: 'blur' }
  ],
  productionDate: [
    { required: true, message: '生产时间不能为空', trigger: 'blur' }
  ],
  inspectionDate: [
    { required: true, message: '质检日期不能为空', trigger: 'blur' }
  ],
  inspectorName: [
    { required: true, message: '质检人员姓名不能为空', trigger: 'blur' }
  ]
});

// 明细数据列表
const planDetailsList = ref([]);
const attachments = ref([]);

// 保存主表单
const addjihau = () => {
  // 表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      axios.post('http://localhost:5293/api/PackagingQuality/AddPackagingQuality', formData)
       .then(response => {
          if (response.data.code === 200) {
            ElMessage.success('完工入库保存成功');
            console.log(response.data.data);
            router.push("/GetPackagingQuality");
          } else {
            ElMessage.error(`完工入库保存失败：${response.data.message}`);
          }
        })
       .catch(error => {
          console.error('保存出错:', error);
          ElMessage.error('保存时出现错误，请检查网络或重试');
        });
    } else {
      ElMessage.error('请填写完整且正确的表单信息');
    }
  });
};

onMounted(() => {
  // 检查函数是否存在
  
    // fetchAssociatedProjects();

 
    fetchAssociatedProjects1();

});

// 对话框显示状态
const associatedItemDialogVisible1 = ref(false);
const currentAssociatedItem1 = ref({});
// 关联项目数据
const associatedItems1 = ref([]);
// 打开关联项目选择对话框
const openAssociatedItemDialog1 = () => {
  associatedItemDialogVisible1.value = true;
};
// 当前选中的关联项目行
const handleAssociatedItemChange1 = (val) => {
  currentAssociatedItem1.value = val;
};
// 选择关联项目
const pickAssociatedItem1 = () => {
  if (currentAssociatedItem1.value) {
    formData.batchNumber = currentAssociatedItem1.value.lotNumber;


    // 确保 formData 中存在这些属性
    // formData.product_model 不存在于 formData 中，可根据实际情况处理或移除
    // formData.production_batch 不存在于 formData 中，可根据实际情况处理或移除
    // formData.production_date 不存在于 formData 中，可根据实际情况处理或移除
    associatedItemDialogVisible1.value = false;
  }
};
// 获取关联项目数据
const fetchAssociatedProjects1 = () => {
  axios.get("http://localhost:5118/api/MaterialPreparation/Handle")
   .then(res => {
      associatedItems1.value = res.data.data;
    })

};
</script>

<style scoped>
.production-plan {
  padding: 30px;
  background-color: #f0f2f5;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  font-family: 'Arial', sans-serif;
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.save-button {
  display: block;
  margin: 0 auto 30px;
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-container {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.el-form-item__label {
  color: #34495e;
  font-size: 16px;
  font-weight: 500;
}

.el-input,
.el-input-number,
.el-date-picker {
  border-radius: 6px;
  border: 1px solid #ccc;
  padding: 10px;
  font-size: 14px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.el-input:focus,
.el-input-number:focus,
.el-date-picker:focus {
  border-color: #42b983;
  outline: none;
  box-shadow: 0 0 5px rgba(66, 185, 131, 0.2);
}
</style>